<?php

namespace Drupal\shusy_distribution\Entity;

use Drupal\shusy_distribution\ViewsController\Traits\ShusyDistributionSexTrait;
use Drupal\shusy_distribution\ViewsController\Traits\ShusyDistributionStatusTrait;
use Entity;

class ShusyDistribution extends Entity {

  public $id;

  public $vid;

  public $uid;

  public $op_uid;

  public $created;

  public $changed;

  public $is_new_revision;

  public $sex;

  public $name;

  public $phone;

  public $bank_no;

  public $bank_name;

  public $address;

  public $reviewer;

  public $level_1;

  public $level_2;

  public $identity_face;

  public $bank_face;

  public $note;

  public $status = 0;

  use ShusyDistributionSexTrait, ShusyDistributionStatusTrait;

  function __construct($values = []) {
    $this->is_new_revision = TRUE;
    parent::__construct($values, 'shusy_distribution');
  }

  public function save() {
    $this->changed = REQUEST_TIME;
    if (empty($this->created)) {
      $this->created = REQUEST_TIME;
    }

    $this->op_uid = $GLOBALS['user']->uid;
    if (empty($this->uid)) {
      $this->uid = $GLOBALS['user']->uid;
    }

    if (!empty($this->bank_face)) {
      $dir = "public://shusy_distribution/bank_face/" . format_date(REQUEST_TIME, 'custom', 'Y/m/d/') . drupal_random_key();
      $result = file_prepare_directory($dir);
      if (empty($result)) {
        drupal_mkdir($dir, 0777, TRUE);
      }
      $file = file_load($this->bank_face);
      if (!empty($file)) {
        $file->status = 1;
        file_save($file);
        $fid = $this->bank_face;
        $ext = pathinfo($file->uri, PATHINFO_EXTENSION);
        $file = file_move($file, "{$dir}/{$fid}.{$ext}");
        file_usage_add($file, 'shusy_distribution', 'bank_face', $file->fid);
      }
    }
    if (!empty($this->identity_face)) {
      $dir = "public://shusy_distribution/identity/" . format_date(REQUEST_TIME, 'custom', 'Y/m/d/') . drupal_random_key();
      $result = file_prepare_directory($dir);
      if (empty($result)) {
        drupal_mkdir($dir, 0777, TRUE);
      }
      $file = file_load($this->identity_face);
      if (!empty($file)) {
        $file->status = 1;
        file_save($file);
        $fid = $this->identity_face;
        $ext = pathinfo($file->uri, PATHINFO_EXTENSION);
        $file = file_move($file, "{$dir}/{$fid}.{$ext}");
        file_usage_add($file, 'shusy_distribution', 'identity_face', $file->fid);
      }
    }

    return parent::save();
  }

}
